import { AfterViewInit, Directive, ElementRef } from '@angular/core';

@Directive({
  selector: 'nav.tabbable'
})
export class StickyScrollNavbarDirective implements AfterViewInit{
  //横行滚动菜单:[appStickyScrollNavbar]
  /*配合样式:
  .tabbable .nav-tabs {
    overflow-x: auto;
    overflow-y:hidden;
    flex-wrap: nowrap;
  }
  .tabbable .nav-tabs .nav-link {
    white-space: nowrap;
    margin:0;
    padding:0 0.5rem
  }
  .tabbable .nav-tabs .nav-link.active{
    border-bottom-color:#007bff;
    background-color:#f6f6f6;
    color:#007bff
  }*/
  //需要指令的下一级元素中含有id="nav-tab"
  constructor(private elementRef: ElementRef) { }

  ngAfterViewInit(): void {
    //小屏幕导航时选中的元素在当前屏幕中可见
    if(window.innerWidth < 767){
      let nav:HTMLElement =this.elementRef.nativeElement.querySelector('#nav-tab')as HTMLElement;
      if(!nav){
        return;
      }
      let focEle:Element = nav.querySelector('a.active') as Element;
      if(!focEle){
        return;
      }
      let ofLeft:number = focEle.getBoundingClientRect().left;
      let eleWidth:number = focEle.getBoundingClientRect().width;
      //FireFox
      nav.scrollTo((ofLeft-eleWidth), 0);
    }
  }
}
